package com.you.bio.socketio;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class SocketServer {


    public static void main(String[] args) throws Exception {
        ExecutorService executorService = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors() * 2);
        ServerSocket serverSocket = new ServerSocket(8080);
        Socket socket = serverSocket.accept();
        executorService.execute(new AcceptProcessImpl(socket));
        executorService.shutdown();
    }

    static class AcceptProcessImpl implements Runnable {

        private Socket socket;

        public AcceptProcessImpl(Socket socket) {
            this.socket = socket;
        }

        @Override
        public void run() {
            try {
                InputStream inputStream = socket.getInputStream();
                OutputStream outputStream = socket.getOutputStream();
                byte[] buff = new byte[100];
                int len;
                String receiveStr = null;
                while ((len = inputStream.read(buff)) != -1) {
                    receiveStr = new String(buff, 0, len);
                    System.out.println(System.currentTimeMillis() + "---接收到：" + receiveStr);
                    outputStream.write(("ok" + receiveStr).getBytes());
                    Thread.sleep(1000L);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
